package se.sll.service.catalogue.common.provider;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

import lombok.extern.slf4j.Slf4j;
import se.sll.service.catalogue.common.exception.ServiceErrorCodeException;

/**
 * Base provider for ServiceErrorCodeException.
 * 
 * @author Christer Palm, Nogui
 */
@Slf4j
public abstract class ServiceErrorCodeExceptionHandler<T extends ServiceErrorCodeException> implements ExceptionMapper<T> {
    private final Response.Status status;

    protected ServiceErrorCodeExceptionHandler(Response.Status status) {
        this.status = status;
    }

    @Override
    public Response toResponse(T e) {
        String message = e.getMessage();
        if (message == null) {
            message = "Unknown error";
        }
        log.info("Exception in REST service", e);
        return Response.
                status(status).
                header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=UTF-8").
                header("X-ErrorCode", e.getErrorCode()).
                entity(message).
                build();
    }
}
